import { iotPush } from "@/api";
import { asyncExecFunction } from "@/king-components/js/KingonPlus";
import store from "@/store";
import dayjs from "dayjs";

// 拉取间隔, 如果获取到的数据为空， 则改为 1 分钟
let delay = 5000;

// 拉取数量
const pullQuantity = 10;

// 定时拉取注册人脸数据
export const signFaceModule = async () => {
  // 获取deviceId
  const did = store.getters.deviceId || store.commit("business/initDeviceId");

  // 拉取人脸数据
  try {
    const pam = {
      action: "ocs_getIncreaseFaceInfo",
      request_id: new Date().getTime(),
      request_time: dayjs().format("YYYY-MM-DD HH:mm:ss"),
      content: {
        device_code: did,
        size: pullQuantity,
        current: 0,
        third_party: "3",
      },
    };
    const { data } = await iotPush(pam);
    console.log("[signFaceModule ] iotPush", data);
    if (data && data.records && data.records.length > 0) {
      await signFaceData(data.records);
      // 将延迟改为 5秒
      delay = 5000;
      // 通知开始
      uni.$emit("signFaceProcess", { status: "start" });
    } else {
      console.warn(
        `[signFaceModule ] 接口未返回更新人脸数据，本地为最新数据, 或当前设备 ${did} 未开通，将延迟轮询间隔`
      );
      // 将延迟改为 1 分钟
      delay = 60 * 1000;
      // 通知结束
      uni.$emit("signFaceProcess", { status: "end" });
    }

    // --- 延迟后再发起请求(调用自身) ----
    reloadSelf();
  } catch (error) {
    // 通知结束
    uni.$emit("signFaceProcess", { status: "end" });
    console.error("[signFaceModule ] 人脸数据拉取/注册失败 ", error);
    // ---失败也需要  延迟后再发起请求(调用自身) ----
    reloadSelf();
  }
};

const reloadSelf = () => {
  // --- 延迟后再发起请求(调用自身) ----
  const currTimer = store.getters.getTimeCode;
  // 如果当前定时器存在，则清除
  if (currTimer) {
    clearTimeout(currTimer);
  }

  // 延时之后再次调用自身达成等待轮询
  const timer = setTimeout(async () => {
    try {
      await signFaceModule();
    } finally {
      clearTimeout(timer);
    }
  }, delay);

  // 存储当前定时器ID
  store.commit("face/setTimerCode", timer);

  // ---------------------------------------
};

const downFaceFile = (face: any) => {
  return new Promise((resolve, reject) => {
    uni.downloadFile({
      url: face.faceUrl, //仅为示例，非真实的接口地址
      // filePath: "/face-data/",
      name: face.cstmName,
      success: (res) => {
        if (res.statusCode === 200) {
          console.log("下载成功", res);
          resolve({ ...face, path: res.tempFilePath, flag: true });
          // uni.saveFile({
          //   tempFilePath: res.tempFilePath, // 文件路径
          //   success: function (saveRes) {
          //     // console.log("文件下载成功，保存路径为：" + saveRes.savedFilePath);
          //     resolve({ ...face, path: saveRes.savedFilePath, flag: true });
          //   },
          //   fail: function (e) {
          //     // console.log("文件下载失败：" + e.errMsg);
          //     resolve({ ...face, path: "", flag: false });
          //   },
          // });
        } else {
          console.log("下载失败", res);
          resolve({ ...face, path: "", flag: false });
        }
      },
    });
  });
};

interface FaceInfo {
  tel: string;
  /** 客户id */
  faceId: string;
  cstmName: string;
  cardId: string;
  faceUrl: string;
}

const signFaceData = async (data: Array<FaceInfo>) => {
  // console.log("开始下载人脸数据", data);
  // const savelist = [];
  // for (const v of data) {
  //   const faceInfo = await downFaceFile(v);
  //   savelist.push(faceInfo);
  //   // console.log("path", path);
  // }

  // console.log(`人脸数据下载完成，下载注册人脸数量${data.length}个,下载成功${savelist.filter((v) => v.flag == true).length}个`);

  const faceJson = JSON.stringify(
    data.map((v) => {
      return {
        faceName: v.faceId,
        faceUrl: v.faceUrl,
      };
    })
  );

  try {
    console.log("[signFaceData ] 将本次获取的人脸数据注册进本地人脸库中, 共", data.length, "个");
    const result = await asyncExecFunction("baiduFaceUrlRegistration", faceJson);
    // if (!Array.isArray(result)) throw new Error("批次人脸注册失败");
    console.log("[signFaceData ] 人脸数据注册完成", result);
  } catch (error) {
    console.error("[signFaceData ] 人脸模块加载失败 init", error);
    // 重新抛出异常
    throw error;
  }
};
